#ifndef __HAL_H
#define __HAL_H

#include "lib/type.h"
#include "lib/bit.h"
#include "N76E003.h"
#include "Common.h"
#include "SFR_Macro.h"
#include <string.h>

#define GPIO_MODE_BD 0	//BIDIRECTIONAL
#define GPIO_MODE_PP 1
#define GPIO_MODE_HI 2	//HIGH IMPEDANCE
#define GPIO_MODE_OD 3

void uart0_use_timer1_init(uint32_t u32Baudrate);
void uart0_send_data_blocked(uint8_t d);
	
void gpio_mode_config(uint8_t port, uint8_t pin, uint8_t mode);
//H, R = 1; L, F = 0;
//level = 1; edge = 0;
void gpio_int_config(uint8_t port, uint8_t pin, uint8_t level_edge, uint8_t H_L_R_F);
void gpio_int_config_clean(void);
#define gpio_int_enable()		set_EPI;
#define gpio_int_disable()		clr_EPI;

uint16_t wakeup_timer_set_next_interrupt_time(uint16_t next_interrupt_time_in_ms);
void wakeup_timer_init_with_calibration(uint8_t time_in_ms);
#define wakeup_timer_start()    set_WKTR
#define wakeup_timer_stop()     clr_WKTR

uint16_t bandgap_volt_read(void);
//when the adc was reseted, first three adc datas should be ignore
uint16_t adc_read(uint8_t channel);
#define adc_enable()			set_ADCEN
#define adc_disable()			clr_ADCEN

void pwm_init(uint16_t frequency_KHz);
void pwm_set(uint8_t channel, uint8_t duty_cycle_in_100);
void pwm_pin_set(uint8_t channel, 
				uint8_t pin_num, uint8_t enable_pin);	//don't forget to set the gpio mode as output
#define pwm_start()				set_PWMRUN;
#define pwm_stop()				clr_PWMRUN;

void timer0_init_40us(void);
#define timer0_start()			set_TR0
#define timer0_stop()			clr_TR0

void timer3_init_10ms(void);
void timer3_set_10ms(uint16_t time);
#define timer3_start()			set_TR3
#define timer3_stop()			clr_TR3

void wdt_init(void);
//#define wdt_enable()			set_WDTR
//#define wdt_disable()			clr_WDTR
#define wdt_feed_dog()			set_WDCLR

#define sleep()					set_PD;
#define idl()					set_IDL;

uint16_t flash_byte_addr_to_page_addr(uint16_t byte_addr);
uint8_t flash_byte_addr_to_byte_offset_in_page(uint16_t byte_addr);
void flash_erase_page_aprom(uint16_t page_addr);	//5ms, auto blocked
uint8_t flash_read_byte(uint16_t byte_addr);
void flash_write_byte_aprom(uint16_t byte_addr, uint8_t wdata);

void delay_20us(volatile uint8_t nCount);
void delay_1ms(volatile uint8_t nCount);

#endif
